#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <time.h>
#include <string.h>
#include <arpa/inet.h>
#include "protocol.h"

#define BUFFSIZE 1024

int serverConnect()
{
    int sockfd;

    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        perror("socket()");
        exit(1);
    }
   
    return sockfd;
}

int main(int argc, char **argv)
{
    
    if (argc < 3)
    {
        fprintf(stdout, "Usage:\n");
        exit(1);
    }

    struct sockaddr_in addr;
    int sockid;
    int ret;
    
    sockid = serverConnect();
    addr.sin_family = AF_INET;
    addr.sin_port = htons(atoi(argv[2]));
    inet_pton(AF_INET, argv[1], &addr.sin_addr);
    
    socklen_t len = sizeof(addr);

    char recvbuff[BUFFSIZE] = {0};
    srand((unsigned int)time(NULL));
	char namebuff[BUFFSIZE] = {0};
	int size;
	struct msg_st *sendbuff;
    while (1)
    {
		fgets(namebuff, BUFFSIZE, stdin);
		if (strlen(namebuff) < NAMESIZE)
		{
			size = sizeof(struct msg_st) + strlen(namebuff);
			sendbuff = malloc(size);
			if (sendbuff == NULL)
			{
				perror("malloc()");
				exit(1);
			}

			sprintf(sendbuff->name, "%s", namebuff);
		}
		else
			exit(0);
        sendbuff->math = htonl(rand()%100);
        sendbuff->English = htonl(rand()%100);
        ret = sendto(sockid, sendbuff, size, 0, (void *)&addr, len);
        if (ret < 0)
        {
            perror("sendto()");
            exit(1);
        }

        ret = recvfrom(sockid, recvbuff, BUFFSIZE, 0, (void *)&addr, &len);  
        if (ret > 0)
        {
            recvbuff[ret] = '\0';
            puts(recvbuff);
        }
        memset(recvbuff, 0, BUFFSIZE);
        sleep(1);
    }
    close(sockid);
}
